package com.ibm.spatiotemp.server.framework.handler;

import org.apache.log4j.Logger;

import com.ibm.spatiotemp.server.datasources.DataSource;
import com.ibm.spatiotemp.server.framework.processor.IndexBuildingProcessor;
import com.ibm.spatiotemp.server.framework.processor.ProcessorFactory;
import com.ibm.spatiotemp.server.framework.processor.RawDataProcessor;
import com.ibm.spatiotemp.server.framework.processor.SpatialQueryProcessor;
import com.ibm.spatiotemp.server.framework.reponse.ResponseFormatter;
import com.ibm.spatiotemp.server.framework.request.Request;
import com.ibm.spatiotemp.server.framework.request.RequestType;

public class DataRequestHandler extends RequestHandler {
	public static Logger logger = Logger.getLogger(DataRequestHandler.class);

	protected DataSource datasrc;
	protected IndexBuildingProcessor indexbuildprocessor;
	protected RawDataProcessor rawdataprocessor;
	protected SpatialQueryProcessor queryprocessor;

	public DataRequestHandler(DataSource src) {
		this.datasrc = src;
		/* get processors instances here from factory according to datasource */
		indexbuildprocessor = ProcessorFactory
				.getIndexBuildingProcessorInstance(src);
		rawdataprocessor = ProcessorFactory.getRawDataProcessorInstance(src);
		queryprocessor = ProcessorFactory.getSpatialQueryProcessorInstance(src);
		if (indexbuildprocessor == null || rawdataprocessor == null
				|| queryprocessor == null) {
			logger.error("processor instance building failed, db_class="
					+ src.getSource_class());
		}
	}

	@Override
	public String handleRequest(Request request) throws Exception {
		String response_body = "";
		// ResponseFormatter
		if (RequestType.Position.equalsIgnoreCase(request.getQtype())) {
			response_body = queryprocessor.handlePositionQuery(request);
		} else if (RequestType.Firsttime.equalsIgnoreCase(request
				.getQtype())) {
			response_body = queryprocessor.handleTimeQuery(request);
		} else if (RequestType.Trajectory.equalsIgnoreCase(request
				.getQtype())) {
			response_body = queryprocessor.handleTrajectoryQuery(request);
		} else if (RequestType.ACTION_WRITEDATA.equalsIgnoreCase(request
				.getQtype())) {
			response_body = rawdataprocessor.handleRawDataInsert(request);
		} else if (RequestType.ACTION_READDATA.equalsIgnoreCase(request
				.getQtype())) {
			String retstring = ResponseFormatter
					.formatTSPointResultSet(rawdataprocessor
							.handleRawDataQuery(request));
			response_body = retstring;
		} else {
			logger.error("unknown query type:" + request.getQtype());
			response_body = "{}";
		}
		return ResponseFormatter.formatResponse(request.getQtype(),
				response_body);
	}
}
